package com.ysw.listener;

import com.ysw.ConfigContext;
import com.ysw.event.SpringValueChangeEvent;
import com.ysw.processor.ConfigProcessor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * @ClassName SpringValueChangeEventListener
 * @Description
 * @Author ysw
 * @Date 2021/10/29 17:03
 */
@Component
public class SpringValueChangeEventListener implements ApplicationListener<SpringValueChangeEvent> {

    @Override
    public void onApplicationEvent(SpringValueChangeEvent springValueChangeEvent) {
        ConfigProcessor processor = getProcessor(springValueChangeEvent.getSource());
        if(checkData(springValueChangeEvent) && null != processor){
            processor.listenConfig(ConfigContext.getExistInstance(), springValueChangeEvent.getKey(), springValueChangeEvent.getValue());
        }
    }

    /**
     * 数据校验
     * @param event
     * @return
     */
    public Boolean checkData(SpringValueChangeEvent event) {
        boolean flag = true;
        if (StringUtils.isBlank(event.getKey()) || StringUtils.isBlank(event.getValue())) {
            flag = false;
        }
        return flag;
    }

    /**
     * 获取processor,类似一种策略模式
     *
     * @param source
     * @return
     */
    private ConfigProcessor getProcessor(Object source) {
        ConfigContext existInstance = ConfigContext.getExistInstance();
        for (ConfigProcessor processor : existInstance.getProcessors()) {
            if (processor.getProcessorType().equals(source)) {
                return processor;
            }
        }
        return null;
    }
}